<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

div {
    position: absolute;
    border-radius: 50%;
}
</style>
</head>
<body>
<script>
function Ball(opt){
    this._init(opt);
}

Ball.prototype = {
    _init: function (opt){
        this.parentNode = opt.parentNode;
        //承载球的那个dom元素
        this.div = document.createElement("div");
        this.r = randomInt(10, 100);
        this.x = randomInt(0, 1000)
        this.y = randomInt(0, 500)
        this.color = `rgba(${randomInt(0, 255)}
                            ,${randomInt(0, 255)}
                            ,${randomInt(0, 255)}
                            ,${Math.random() * 0.6 + 0.4})`
        this.speedX = randomInt(-20, 20);
        this.speedY = randomInt(-20, 20);

    },
    show: function (){
        var div = this.div;
        div.style.width = this.r * 2 + "px";
        div.style.height = this.r * 2 + "px";
        div.style.backgroundColor = this.color;
        div.style.left = this.x + "px";
        div.style.top = this.y + "px";
        this.parentNode.appendChild(div);
    },
    move: function (){
        var div = this.div;
        var directionX = 1;
        var directionY = 1;
        var maxLeft = this.parentNode.offsetWidth - div.offsetWidth;
        var maxTop = this.parentNode.offsetHeight - div.offsetHeight;
        var speedX = this.speedX;
        var speedY = this.speedY;
        setTimeout(function step(){
            // 检测是否到了边缘
            if (div.offsetLeft <= 0 || div.offsetLeft >= maxLeft){
                directionX *= -1;
            }
            if (div.offsetTop <= 0 || div.offsetTop >= maxTop){
                directionY *= -1;
            }

            var left = div.offsetLeft + speedX * directionX;
            var top = div.offsetTop + speedY * directionY;

            left = left <= 0 ? 0 : left;
            top = top <= 0 ? 0 : top;
            left = left >= maxLeft ? maxLeft : left;
            top = top >= maxTop ? maxTop : top;

            div.style.left = left + "px"
            div.style.top = top + "px"

            setTimeout(step, 40)
        }, 20)
    }
}

for (var i = 0; i < 30; i++){
    var b = new Ball({parentNode: document.body})
    b.show();
    b.move()
}

/**
 作者:李振超      2017年8月16日 16:57
 返回随机的 [from, to] 之间的整数(包括from，也包括to)
 */
function randomInt(from, to){
    return parseInt(Math.random() * (to - from + 1) + from);
}

</script>
</body>
</html>